/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package cn.laike.common.utils;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;

/**
 * Redis工具类
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-07-17 21:12
 */
@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource(name="redisTemplate")
    private ValueOperations<String, String> valueOperations;
    @Resource(name="redisTemplate")
    private HashOperations<String, String, Object> hashOperations;
    @Resource(name="redisTemplate")
    private ListOperations<String, Object> listOperations;
    @Resource(name="redisTemplate")
    private SetOperations<String, Object> setOperations;
    @Resource(name="redisTemplate")
    private ZSetOperations<String, Object> zSetOperations;
    /**  默认过期时长，单位：秒 */
    public final static long DEFAULT_EXPIRE = 60 * 60 * 24;
    /**  不设置过期时长 */
    public final static long NOT_EXPIRE = -1;

    public void set(String key, Object value, long expire){
        valueOperations.set(key, toJson(value));
        if(expire != NOT_EXPIRE){
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }

    public void set(String key, Object value){
        set(key, value, DEFAULT_EXPIRE);
    }

    public <T> T get(String key, Class<T> clazz, long expire) {
        String value = valueOperations.get(key);
        if(expire != NOT_EXPIRE){
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value == null ? null : fromJson(value, clazz);
    }

    public <T> T get(String key, Class<T> clazz) {
        return get(key, clazz, NOT_EXPIRE);
    }

    public String get(String key, long expire) {
        String value = valueOperations.get(key);
        if(expire != NOT_EXPIRE){
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value;
    }

    public String get(String key) {
        return get(key, NOT_EXPIRE);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    /**
     * Object转成JSON数据
     */
    private String toJson(Object object){
        if(object instanceof Integer || object instanceof Long || object instanceof Float ||
                object instanceof Double || object instanceof Boolean || object instanceof String){
            return String.valueOf(object);
        }
        return JSON.toJSONString(object);
    }

    /**
     * JSON数据，转成Object
     */
    private <T> T fromJson(String json, Class<T> clazz){
        return JSON.parseObject(json, clazz);
    }

    /**********************************common****************************************/
 	/**
      * 指定缓存失效时间
      * @param key 键
      * @param time 时间(秒)
      * @return
      */
 	public boolean expire(String key, long time) {
         try {
             if (time > 0) {
                 redisTemplate.expire(key, time, TimeUnit.SECONDS);
             }
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }
     /**
      * 根据key 获取过期时间
      * @param key 键 不能为null
      * @return 时间(秒) 返回0代表为永久有效
      */
     public long getExpire(String key) {
         return redisTemplate.getExpire(key, TimeUnit.SECONDS);
     }
     /**
      * 判断key是否存在
      * @param key 键
      * @return true 存在 false不存在
      */
     public boolean hasKey(String key) {
         try {
             return redisTemplate.hasKey(key);
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }
     /**
      * 删除缓存
      * @param key 可以传一个值 或多个
      */
     @SuppressWarnings("unchecked")
     public void del(String... key) {
         if (key != null && key.length > 0) {
             if (key.length == 1) {
                 redisTemplate.delete(key[0]);
             } else {
                 redisTemplate.delete(CollectionUtils.arrayToList(key));
             }
         }
     }
     /**********************************common****************************************/
     
     /**********************************设置缓存****************************************/
     /**
      * 普通缓存获取
      * @param key 键
      * @return 值
      */
     public Object getString(String key) {
         return key == null ? null : valueOperations.get(key);
     }
     /**
      * 普通缓存放入
      * @param key 键
      * @param value 值
      * @return true成功 false失败
      */
     public boolean setString(String key, String value) {
         try {
        	 valueOperations.getAndSet(key, value);
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }
     /**
      * 普通缓存放入并设置时间
      * @param key 键
      * @param value 值
      * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
      * @return true成功 false 失败
      */
     public boolean setString(String key, String value, long time) {
         try {
             if (time > 0) {
            	 valueOperations.set(key, value, time, TimeUnit.SECONDS);
             } else {
                 set(key, value);
             }
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }
     
     /**
      * 普通缓存获取
      * @param key 键
      * @return 值
      */
     public Object getObject(String key) {
         return key == null ? null : redisTemplate.opsForValue().get(key);
     }
     /**
      * 普通缓存放入
      * @param key 键
      * @param value 值
      * @return true成功 false失败
      */
     public boolean setObject(String key, Object value) {
         try {
             redisTemplate.opsForValue().set(key, value);
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }
     /**
      * 普通缓存放入并设置时间
      * @param key 键
      * @param value 值
      * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
      * @return true成功 false 失败
      */
     public boolean setObject(String key, Object value, long time) {
         try {
             if (time > 0) {
                 redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
             } else {
                 set(key, value);
             }
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }
     /**
      * 递增
      * @param key 键
      * @param delta 要增加几(大于0)
      * @return
      */
     public long incr(String key, long delta) {
         if (delta < 0) {
             throw new RuntimeException("递增因子必须大于0");
         }
         return redisTemplate.opsForValue().increment(key, delta);
     }
     /**
      * 递减
      * @param key 键
      * @param delta 要减少几(小于0)
      * @return
      */
     public long decr(String key, long delta) {
         if (delta < 0) {
             throw new RuntimeException("递减因子必须大于0");
         }
         return redisTemplate.opsForValue().increment(key, -delta);
     }
     /**********************************设置缓存****************************************/
     
     // ===============================list=================================


     /**
      * 获取list缓存的内容
      * @param key 键
      * @param start 开始
      * @param end 结束 0 到 -代表所有值
      * @return
      */
     public List<Object> lGet(String key, long start, long end) {
         try {
             return redisTemplate.opsForList().range(key, start, end);
         } catch (Exception e) {
             e.printStackTrace();
             return null;
         }
     }
     /**
      * 获取list缓存的长度
      * @param key 键
      * @return
      */
     public long lGetListSize(String key) {
         try {
             return redisTemplate.opsForList().size(key);
         } catch (Exception e) {
             e.printStackTrace();
             return 0;
         }
     }


     /**
      * 通过索引 获取list中的值
      * @param key 键
      * @param index 索引 index>=0时， 0 表头， 第二个元素，依次类推；index<0时，-，表尾，-倒数第二个元素，依次类推
      * @return
      */
     public Object lGetIndex(String key, long index) {
         try {
             return redisTemplate.opsForList().index(key, index);
         } catch (Exception e) {
             e.printStackTrace();
             return null;
         }
     }
     /**
      * 将list放入缓存
      * @param key 键
      * @param value 值
      * @param time 时间(秒)
      * @return
      */
     public boolean lSet(String key, Object value) {
         try {
             redisTemplate.opsForList().rightPush(key, value);
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }


     /**
      * 将list放入缓存
      * @param key 键
      * @param value 值
      * @param time 时间(秒)
      * @return
      */
     public boolean lSet(String key, Object value, long time) {
         try {
             redisTemplate.opsForList().rightPush(key, value);
             if (time > 0)
                 expire(key, time);
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }


     /**
      * 将list放入缓存
      * @param key 键
      * @param value 值
      * @param time 时间(秒)
      * @return
      */
     public boolean lSet(String key, List<Object> value) {
         try {
             redisTemplate.opsForList().rightPushAll(key, value);
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }
     /**
      * 将list放入缓存
      * @param key 键
      * @param value 值
      * @param time 时间(秒)
      * @return
      */
     public boolean lSet(String key, List<Object> value, long time) {
         try {
             redisTemplate.opsForList().rightPushAll(key, value);
             if (time > 0)
                 expire(key, time);
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }
     /**
      * 根据索引修改list中的某条数据
      * @param key 键
      * @param index 索引
      * @param value 值
      * @return
      */
     public boolean lUpdateIndex(String key, long index, Object value) {
         try {
             redisTemplate.opsForList().set(key, index, value);
             return true;
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
     }
     /**
      * 移除N个值为value
      * @param key 键
      * @param count 移除多少个
      * @param value 值
      * @return 移除的个数
      */
     public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    public static void main(String[] args) {
	}
}
